import {Injectable} from '@angular/core';
import {Headers, Http} from '@angular/http';
import {ParamConfig} from '../common/param.config';
import 'rxjs/add/operator/toPromise';
import {AppEditionPage, AppEdition} from './appEdition';
import {Router} from '@angular/router';
import {UserService} from '../user/user.service';

@Injectable()
export class AppEditionService {
  public token: string;
  private hostUrl = ParamConfig.HTTP_WEB_HOST_URL + 'web/version/listVersion'; // 查询app
  private hostUrlAddApp = ParamConfig.HTTP_WEB_HOST_URL + 'web/version/saveVersion'; // 保存app
  private hostUrlUpdateApp = ParamConfig.HTTP_WEB_HOST_URL + 'web/version/updateVersion'; // 修改app
  private hostUrlDeleteApp = ParamConfig.HTTP_WEB_HOST_URL + 'web/version/deleteVersion';
  private hostUrlCompany = ParamConfig.HTTP_WEB_HOST_URL + 'company/getAllCompany';

  constructor(private http: Http, private userService: UserService, private router: Router) {
  };

  // 公司查询
  getCompanyService(): Promise<any> {
    const request = JSON.stringify({});
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlCompany, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            return [true, body.datas];
          }
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

  // 查询app
  getAppEdition(page): Promise<any> {
    const request = JSON.stringify({
      rows: ParamConfig.DATA_LIST_PAGE_SIZE,
      page: page,
      criteria: {
        companySign: ''
      }
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrl, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            const pagedata = new AppEditionPage();
            pagedata.appEdition = body as AppEdition[];
            pagedata.totalPages = body.total;
            return pagedata;
          }
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

  // 增加app
  addAppEdition(appEdition: AppEdition, companyId): Promise<any> {
    const request = JSON.stringify({
      number: appEdition.number,
      type: appEdition.type,
      isCompelUp: appEdition.isCompelUp,
      url: appEdition.url,
      companySign: companyId
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlAddApp, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            return true;
          }
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

  // 修改app
  updateAppinfo(appEdition: AppEdition, appIdInfo): Promise<any> {
    const request = JSON.stringify({
      id: appIdInfo,
      number: appEdition.number,
      type: appEdition.type,
      isCompelUp: appEdition.isCompelUp,
      url: appEdition.url,
      companySign: appEdition.companySign
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlUpdateApp, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            return true;
          }
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

// 删除app
  removeUserinfo(idInfo): Promise<any> {
    const request = JSON.stringify({
      id: idInfo
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlDeleteApp, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === '1') {
            return true;
          }
          if (body.status === '2') {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<[boolean, any]> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject([false, error.toString()]);
  }
}
